<?php
class Ui_Form {
	protected $pool_form = array ();
	protected $pool_data = array ();
	protected $pool_html = array ();
	
	protected function parseYaml($file) {
		Mid::loadLib ( 'spyc/spyc' );
		$data = Spyc::YAMLLoad ( $file );
		return $data;
	}
	
	protected function parseData($name, $ext = '.form') {
		if (isset ( $this->pool_data [$name] ))
			return $this->pool_data [$name];
		$form_dir = 'm/form/';
		$path = Mid::path ( $form_dir . $name . $ext, false );
		$data = $this->parseYaml ( $path );
		$default = array ('attr' => array ('action' => '', 'method' => 'post', 'name' => 'form_mid' ), 'submit' => array ('value' => '提交信息' ) );
		$this->array_merge_default ( $data, $default );
		$this->pool_data [$name] = $data;
		return $data;
	}
	
	protected function toHtml($name) {
		if (isset ( $this->pool_html [$name] ))
			return $this->pool_html [$name];
		if (isset ( $this->pool_data [$name] ))
			$data = $this->pool_data [$name];
		else
			$data = $this->parseData ( $name );
			
		$html = '';
		foreach ( $data as $key => $value ) {
			if($key == 'attr'){
				$attr_inline = '';
				foreach ($value as $k=>$v){
					$attr_inline.= " {$k}='{$v}'";
				}
			}
			$html.= "<form{$attr_inline}>\n";
			$html.= '<table width="100%" cellspacing=0 cellpadding=0>\n';
			if($key == 'line'){
				$line = '';
				foreach ($value as $v){
					if(isset($v['elem'])){
						foreach ($v['elem'] as $type => $elem){
							
						}
					}
					if(isset($v['tip'])){
										
					}
				}
			}
		}
		//return $html;
	}
	
	public function parse($name) {
		//return $html;
	}
	
	protected function array_merge_default(&$array, $default) {
		if (empty ( $array )) {
			$array = $default;
			return;
		}
		foreach ( $default as $key => $value ) {
			if (! isset ( $array [$key] )) {
				$array [$key] = $value;
			} else {
				if (is_array ( $value ) && is_array ( $array [$key] ))
					$this->array_merge_default ( $array [$key], $value );
			}
		}
	}
}
?>